//
//  HomeStatesListViewModel.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/11.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import Foundation

private let mostPullupCount = 3 // 允许最大的上啦刷新次数


class HomeStatesListViewModel {
    
    var statesList = [MSStatesViewModel]()
    
    var nullPullUpCount = 0 //用于记录上拉次数
    
    
    func loadStates(isPullup: Bool, completion: (statesList: [MSStatesViewModel], isSuccess: Bool, shouldRefresh: Bool)->()) {
        
        let since_id = !isPullup ? statesList.first?.statesModel.id ?? 0 : 0
        let max_id = isPullup ? statesList.last?.statesModel.id ?? 0 : 0
        
        if isPullup && nullPullUpCount > mostPullupCount {
            
            completion(statesList: statesList, isSuccess: true, shouldRefresh: false)
            return
        }
        
        MSAFNManage.shared.statesListRequest(since_id: since_id, max_id: max_id) { (statesList, isSuccess) in
            
            if !isSuccess {
                return
            }
            
            var array = [MSStatesViewModel]()
            
            for dict in statesList ?? [] {
                
                let stateMode = MSStatesModel()
                
                stateMode.yy_modelSet(with: dict)
                
                let stateViewMode = MSStatesViewModel(statesModel: stateMode)
                
                array.append(stateViewMode)
            }
            
            if array.count == 0 && isPullup {
                self.nullPullUpCount += 1
                completion(statesList: self.statesList, isSuccess: isSuccess, shouldRefresh: false)
            } else {
                if isPullup {
                    self.statesList += array
                } else {
                    self.statesList = array + self.statesList
                }
                
                
                print("刷新了\(array.count)条微博")
                completion(statesList: self.statesList, isSuccess: isSuccess, shouldRefresh: true)
            }
            
            
            
            
        }
        
    }

}
